package com.ubhave.powertracker;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

public class LifeGuideConnector{
	
	String URL;
	String restURL;
	
	SharedPreferences settings;
	SharedPreferences.Editor editor;
	
	Activity act;
			
	//This is the constructor most objects use.
	public LifeGuideConnector(SharedPreferences sp){
		
		settings=sp;
		editor=settings.edit();
	    
		URL= settings.getString("LifeGuideURL", "");
		restURL = URL+"/rest";
		Log.i("POWeR Tracker: ", "LifeGuide Connector Created "+restURL);
		
		
	}
	
	public LifeGuideConnector(SharedPreferences sp, Activity a){
		
		settings=sp;
		editor=settings.edit();
	    
		URL= settings.getString("LifeGuideURL", "");
		restURL = URL+"/rest";
		Log.i("POWeR Tracker: ", "LifeGuide Connector Created "+restURL);
		
		act=a;
		
		
	}
	
		
	public String getVar(String inte, String usr, String type, String var, String authkey) throws PowerTrackerInvalidAuthKeyException{
    	Log.i("POWeR Tracker: ", "Web Service Variable Request");
    	
    	String res = "";
    	res = getHttp("/"+inte+"/"+usr+"/"+type+"/"+var, authkey);
    	
    	return parseXML(res);
    }
	
	public String postVar(String inte, String usr, String type, String var, String val, String authkey) throws PowerTrackerInvalidAuthKeyException{
		
		String xml = "<?xml version='1.0' encoding='utf-8'?><data date='"+new Date()+"'><intervention id='"+inte+"'><user identifier='"+usr+"'><dataset type='"+type+"'><variable identifier='"+var+"'>"+val+"</variable></dataset></user></intervention></data>";
	    
		String res = "";
		
		try{
			res = postHttp("/"+inte+"/"+usr+"/"+type+"/"+var, xml, authkey);
		}
		catch(UnsupportedEncodingException e){
			e.printStackTrace();
			Log.e("POWeR Tracker: ", "POST ERROR: "+e+" "+"/"+inte+"/"+usr+"/"+type+"/"+var);
		}
			
    	return res;
		
	}
	
	
	public String getHttp(String queryURL, String authkey) throws PowerTrackerInvalidAuthKeyException{
		Log.i("POWeR Tracker", "Making GET Request "+ restURL + queryURL);
    	
    	HttpClient httpclient = new DefaultHttpClient();
    	           
    	HttpGet request = new HttpGet(restURL + queryURL);
        request.addHeader("deviceId", "xxxxx"); 
        request.addHeader("authkey",authkey);
        
        ResponseHandler<String> handler = new BasicResponseHandler(); 
        HttpResponse response = null;
      
        
        String result="DEFAULT GET RESULT";
        Log.i("POWeR Tracker: ", "HttpClient Created");
        try {  
        		response = httpclient.execute(request);
        		result = handler.handleResponse(response);
        		Log.i("POWeR Tracker", "GET Request at "+restURL + queryURL+" response "+result);
       
        } catch (ClientProtocolException e) {  
        	result = e.toString();
        	e.printStackTrace();
        	Log.i("POWeR Tracker", "GET Fail "+ e);
        } catch (IOException e) {
        	result = e.toString();
            e.printStackTrace();
            Log.i("POWeR Tracker", "GET Fail "+ e);
        }  
        httpclient.getConnectionManager().shutdown();  
        
                
        if(response!=null&&(response.getStatusLine().getStatusCode()==200||response.getStatusLine().getStatusCode()==500))
        	return result;
        else if(response!=null&&response.getStatusLine().getStatusCode()==401)
        	throw new PowerTrackerInvalidAuthKeyException();
        else
        	return "Fail";
        
        
	}
	
	public String parseXML(String xml){
		
		Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
 
            DocumentBuilder db = dbf.newDocumentBuilder();
 
            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is); 
 
            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }
                // return DOM
        
            
            
            NodeList n = doc.getElementsByTagName("variable");
            Node elem = n.item(0);

            Node child;
            if( elem != null){
                if (elem.hasChildNodes()){
                    for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                        if(child.getNodeType() == Node.TEXT_NODE ){
                        	Log.i("POWeR Tracker", "XML "+(elem.getAttributes()).getNamedItem("identifier").getTextContent());
                        	return child.getNodeValue();
                        }
                    }
                }
            }
            return null;
            
		
	}
	
	
	
	public String postHttp(String queryURL, String xml, String authkey) throws UnsupportedEncodingException, PowerTrackerInvalidAuthKeyException{
		
		HttpClient httpclient = new DefaultHttpClient();  
        
		//Log.i("POWeR Tracker: ", "POST CHECK: "+restURL+queryURL);
		HttpPost request = new HttpPost(restURL+queryURL);
		
		
		request.addHeader("deviceId", "xxxxx");
              
        request.addHeader("Content-Type", "text/xml");
        
        request.addHeader("authkey",authkey);
               
        request.setEntity(new StringEntity(xml));
              
        HttpResponse response=null;
        ResponseHandler<String> handler = new BasicResponseHandler();
        String result="";
        try {
        response = httpclient.execute(request);
        result=handler.handleResponse(response);
        }
        catch (ClientProtocolException e) {
        	e.printStackTrace();  
        } catch (IOException e) {
        	e.printStackTrace();  
        }
        httpclient.getConnectionManager().shutdown(); 
        
        //Log.i("POWeR Tracker Special: ","POST Check: "+response+" "+response.getStatusLine().getStatusCode());
        
        if(response!=null&&response.getStatusLine().getStatusCode()==200)
        	return result;
        else if(response!=null&&response.getStatusLine().getStatusCode()==401)
        	throw new PowerTrackerInvalidAuthKeyException();
        else
        	return "Fail";
        
	}
	
	public boolean loginPost(String un, String pw, String inte){
		
		HttpClient httpclient = new DefaultHttpClient();  
        
		HttpPost request = new HttpPost(restURL+"authentication/"+inte);
		//Log.i("POWeR Tracker Special: ","LOGIN POST 0: "+restURL+"authentication");
				
		request.addHeader("deviceId", "xxxxx");
              
        //request.addHeader("Content-Type", "text/xml");
        
        String md5pw="";
        try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			Log.i("POWeR Tracker Special: ","LOGIN: "+un+" "+pw);
			md5pw = new BigInteger(1,md.digest(pw.getBytes("UTF-8"))).toString(16);
			if(md5pw.length()==39){
				md5pw="0"+md5pw;
			}
			
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Log.i("POWeR Tracker Special: ","LOGIN POST 1: "+un+" "+md5pw);
		
        
        request.addHeader("un",un);
        request.addHeader("pw",md5pw);
               
        ResponseHandler<String> handler = new BasicResponseHandler(); 
        
        HttpResponse response=null;
        
        String result="";
        
        //Log.i("POWeR Tracker Special: ","LOGIN POST 2: ");
        
        try {
        //Log.i("POWeR Tracker Special: ","LOGIN POST 3: ");
        response = httpclient.execute(request);
        result=handler.handleResponse(response);
        //Log.i("POWeR Tracker Special: ","LOGIN POST 4: ");
        }
        catch (ClientProtocolException e) {
        	e.printStackTrace();
        	Log.i("POWeR Tracker Special: ","LOGIN Error: "+e);
        } catch (IOException e) {
        	e.printStackTrace();
        	Log.i("POWeR Tracker Special: ","LOGIN Error: "+e);
        }
        catch (Exception e){
        	Log.i("POWeR Tracker Special: ","LOGIN Error: "+e);
        }
        httpclient.getConnectionManager().shutdown(); 
        
        //Log.i("POWeR Tracker Special: ","LOGIN POST 5: "+result+" "+response.getStatusLine().getStatusCode());
        
        if(response!=null&&response.getStatusLine().getStatusCode()==200){
            editor.putString("authkey", result);
            editor.commit();
        	return true;
        }
        else
        	return false;
		
	}
	
	
	
	
}